package com.hqj.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 属性类的练习
 * @author HQJ
 * 利用properties的一些特定属性与知识，完成对一个字符串的字符进行分类统计
 * 把结果写入到test1.properties,文件中，并用下面的方式进行显示
 * 如字符串：123accxc 结果:1-1,2-1,3-1,a-1,c-3,x-1
 *
 *  pro.containsKey("1");
 */
public class Exercise01 {
    public static void main(String[] args) throws Exception{
        Exercise01 e01 = new Exercise01();
        Properties pro = e01.getCharCount("1234567879qdsf");

        File f = new File("E:\\Entor\\jsd202006\\frms");
        e01.createDir(f);
        File f1 = new File(f,"test1.properties");
        e01.createFile(f1);

        e01.outputPro(f1,pro);
        Thread.sleep(2000);

        pro = e01.inputPro(f1);
        boolean b = false;
        //从属性类中取值
        for(Object obj:pro.keySet()){
            String key = obj+"";
            String value = pro.getProperty(key);

            if(b)System.out.print(",");
            b = true;

            System.out.print(key+"-"+value);


        }

    }

    public void outputPro(File f,Properties pro){
        try {
            FileOutputStream fos = new FileOutputStream(f);

            //执行写出
            pro.store(fos,"");

            //关闭
            fos.close();
        }catch (Exception e){

        }
    }

    public Properties inputPro(File f){
        Properties pro = new Properties();
        try {
            FileInputStream fis = new FileInputStream(f);
            //加载
            pro.load(fis);
            //关闭
            fis.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return pro;
    }


    public Properties getCharCount(String str){//123ccx
        Properties pro = new Properties();
        char cs[] = str.toCharArray();
        for (char c:cs){
            int count = 1;
            if(pro.containsKey(c+"")){
                count = Integer.parseInt(pro.getProperty(c+""));
                count++;
            }
            pro.setProperty(c+"",count+"");//key存在就会覆盖
        }
        return pro;
    }

    //创建路径
    public void createDir(File f){
        if(!f.exists()){
            f.mkdirs();
        }
    }

    //创建新文件
    public void createFile(File f){
        try {
            if(!f.exists()){
                f.createNewFile();
            }
        }catch (Exception e){
            System.out.println("文件创建失败，路径有误!"+e.getMessage());
        }
    }

}
